package org.compiere.model;

import java.awt.Container;
import java.io.File;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;

import javax.swing.JFrame;

import org.compiere.apps.IProcessParameter;
import org.compiere.apps.ProcessCtl;
import org.compiere.apps.ProcessParameterPanel;
import org.compiere.apps.Waiting;
import org.compiere.process.DocAction;
import org.compiere.process.DocumentEngine;
import org.compiere.process.ProcessInfo;
import org.compiere.process.ProcessInfoParameter;
import org.compiere.util.ASyncProcess;
import org.compiere.util.CCache;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Msg;

public class Mhrmcheckoff extends X_hrm_checkoff implements DocAction, ASyncProcess {


	/**
	 * 
	 */
	private static final long serialVersionUID = -698556430551095979L;
	
	private int AD_Process_ID;
	/**/
	ASyncProcess m_parent;

	public Mhrmcheckoff(Properties ctx) {
		super(ctx);
		
	}

	public Mhrmcheckoff(Properties ctx, int hrm_checkoff_ID, String trxName) {
		super(ctx, hrm_checkoff_ID, trxName);
		
	}
	
	public Mhrmcheckoff(Properties ctx, ResultSet rs, String trxName) {
		super(ctx, rs, trxName);
	
	}
	
	/**	Checkoff Lines	*/
	private Mhrmcheckoffline[] m_lines;
	private X_hrm_checkoffline[] m_linesacct;
	
	/**
	 * 	Get HR Checkoff Lines
	 * 	@param whereClause starting with AND
	 * 	@return lines
	 */
	private Mhrmcheckoffline[] getLinesCheckoff (String whereClause)
	{
		String whereClauseFinal = "hrm_checkoff_ID=? ";
		if (whereClause != null)
			whereClauseFinal += whereClause;
		List<Mhrmcheckoffline> list = new Query(getCtx(), I_hrm_checkoff_line.Table_Name, whereClauseFinal, get_TrxName())
										.setParameters(gethrm_checkoff_ID())
										.list();
		return list.toArray(new Mhrmcheckoffline[list.size()]);
	}	//	getLines
	
	/**
	 * 	Get Checkoff Lines
	 * 	@param requery
	 * 	@return lines
	 */
	public Mhrmcheckoffline[] getLinesCheckoff (boolean requery)
	{
		if (m_lines == null || m_lines.length == 0 || requery)
			m_lines = getLinesCheckoff(null);
		set_TrxName(m_lines, get_TrxName());
		return m_lines;
	}	//	getLines
	/**
	 * 	Get Checkoff line
	 * 	@return lines
	 */
	public Mhrmcheckoffline[] getLinesCheckoff()
	{
		return getLinesCheckoff(false);
	}	//	getLines
	
	/**
	 * 	Get HR Checkoff Lines
	 * 	@param whereClause starting with AND
	 * 	@return lines
	 */
	private X_hrm_checkoffline[] getLinesCheckoffAcct (String whereClause)
	{
		String whereClauseFinal = "hrm_checkoff_ID=? ";
		if (whereClause != null)
			whereClauseFinal += whereClause;
		List<X_hrm_checkoffline> list = new Query(getCtx(), I_hrm_checkoffline.Table_Name, whereClauseFinal, get_TrxName())
										.setParameters(gethrm_checkoff_ID())
										.list();
		return list.toArray(new X_hrm_checkoffline[list.size()]);
	}	//	getLines

	/**
	 * 	Get Checkoff Lines
	 * 	@param requery
	 * 	@return lines
	 */
	public X_hrm_checkoffline[] getLinesCheckoffAcct (boolean requery)
	{
		if (m_linesacct == null || m_linesacct.length == 0 || requery)
			m_linesacct = getLinesCheckoffAcct(null);
		set_TrxName(m_linesacct, get_TrxName());
		return m_linesacct;
	}	//	getLines

	/**
	 * 	Get Checkoff line
	 * 	@return lines
	 */

	public X_hrm_checkoffline[] getLinesCheckoffAcct()
	{
		return getLinesCheckoffAcct(false);
	}	//	getLines
	
	public void setProcessed (boolean processed)
	{
		super.setProcessed (processed);
		if (get_ID() == 0)
			return;
		String set = "SET Processed='"
			+ (processed ? "Y" : "N")
			+ "' WHERE hrm_Checkoff_ID = " + gethrm_checkoff_ID();
		int succes = DB.executeUpdate("UPDATE hrm_checkoff " + set, get_TrxName());
	}	//	setProcessed
	
	public String prepareIt()
	{
		log.info(toString());
		m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_PREPARE);
		if (m_processMsg != null)
			return DocAction.STATUS_Invalid;

		//	Convert/Check DocType
		if (getC_DocType_ID() == 0)
		{
			m_processMsg = "No Document Type";
			return DocAction.STATUS_Invalid;
		}

		m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_PREPARE);
		if (m_processMsg != null)
			return DocAction.STATUS_Invalid;

		//	Add up Amounts
		m_justPrepared = true;
		if (!DOCACTION_Complete.equals(getDocAction()))
			setDocAction(DOCACTION_Complete);
		return DocAction.STATUS_InProgress;
	}	//	prepareIt	
	
	public boolean processIt (String processAction)
	{
		m_processMsg = null;
		DocumentEngine engine = new DocumentEngine (this, getDocStatus());
		return engine.processIt (processAction, getDocAction());
	}	//	process
	
	

	/**	Process Message 			*/
	private String		m_processMsg = null;
	/**	Just Prepared Flag			*/
	private boolean		m_justPrepared = false;

	private Waiting m_waiting;
	

	public void lockUI(ProcessInfo pi) {
		JFrame frame = Env.getFrame((Container)m_parent);
		m_waiting = new Waiting (frame, Msg.getMsg(Env.getCtx(), "Processing"), false, pi.getEstSeconds());
		
	}
	
	public void unlockUI(ProcessInfo pi) {

		if (m_waiting != null)
			m_waiting.dispose();
		m_waiting = null;	}

	@Override
	public boolean isUILocked() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void executeASync(ProcessInfo pi) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean unlockIt() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean invalidateIt() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean approveIt() {
		log.info(toString());
		setIsApproved(true);
		return true;
	}
	
	public boolean rejectIt() {
		// TODO Auto-generated method stub
		return false;
	}
	
	protected void getAD_Process_ID() {
		
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		// 
		String sql_ = "select distinct t.ad_process_id from ad_process t \n "+ 
					  "where (lower(t.value) like lower('GenerateCheckOff') or lower(t.name) like lower('GenerateCheckoff')) "+ 
				      "and t.isactive='Y'";
		try
		{
			pstmt = DB.prepareStatement(sql_, null);
			rs = pstmt.executeQuery();
			if (rs.next())
				AD_Process_ID = rs.getInt(1);
		}
		catch (SQLException e)
		{
			log.log(Level.SEVERE, "product", e);
		}
		finally
		{
			DB.close(rs, pstmt);
			rs = null; pstmt = null;
		}
	}	

	public String completeIt() {
		getAD_Process_ID();
		
		if(AD_Process_ID != 0){
			//  Prepare Process
			ProcessInfo pi = new ProcessInfo ("The printing process of ", AD_Process_ID);
			pi.setAD_User_ID (Env.getAD_User_ID(Env.getCtx()));
			pi.setAD_Client_ID(Env.getAD_Client_ID(Env.getCtx()));
			pi.setRecord_ID(get_ID());

			List<ProcessInfoParameter> po = new ArrayList<ProcessInfoParameter>();
			po.add(new ProcessInfoParameter("CloseTax","Y",null,"",""));
			//
			ProcessInfoParameter[] pp = new ProcessInfoParameter[po.size()];
			po.toArray(pp);
			pi.setParameter(pp);
			//	Execute Process
			ProcessParameterPanel pu = new ProcessParameterPanel(0, pi);
			ProcessCtl.process(this, 0, (IProcessParameter) pu, pi, null);
		}
		
		//	Re-Check
		if (!m_justPrepared)
		{
			String status = prepareIt();
			if (!DocAction.STATUS_InProgress.equals(status))
				return status;
		}

		m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_COMPLETE);
		if (m_processMsg != null)
			return DocAction.STATUS_Invalid;
//
//		//	Implicit Approval
		if (!isApproved())
			approveIt();
		log.info(toString());
		
		StringBuffer info = new StringBuffer();
		
		m_processMsg = info.toString().trim();
		setProcessed(true);
//		save();
		setDocAction(DOCACTION_Close);
		return DocAction.STATUS_Completed;	
	}

	
	public boolean voidIt() {
		boolean result = true;
		if (!haveCorrectDocument()) {
			if ( DocAction.STATUS_Completed.equals(getDocStatus()) && isPosted()) {
				result = reverseCorrectIt();
			}
			if (result) {
				setProcessed(true);
				setDocAction(DOCACTION_None);
			}
		} else {
			result = false;
		}
		return result;	
	}
	
	/**
	 * @return
	 */
	public boolean haveCorrectDocument() {
		boolean result = getReversal_ID() > 0;
		return result;
	}

	public boolean closeIt() {
		log.info(toString());
		// Before Close
		m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_CLOSE);
		if (m_processMsg != null)
			return false;

		setProcessed(true);
		setDocAction(DOCACTION_None);

		// After Close
		m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_CLOSE);
		if (m_processMsg != null)
			return false;
		return true;	
	}

	public boolean reverseCorrectIt() {
		boolean result = false;
		log.info(toString());
		if (!haveCorrectDocument()) {
			result = createCorrectDocument();
		}
		return result;
	}
	
	/**
	 * @return
	 */
	private boolean createCorrectDocument() {
		Mhrmcheckoff reversal = copyFrom (this, getStartDate(), getEndDate(), getDateAcct(), get_TrxName());
		if (reversal == null) {
			m_processMsg = "Could not create CheckOff document Reversal";
			return false;
		}
		reversal.setReversal(true);
		reversal.setName("Canceled -> " + reversal.getName());
		reversal.addDescription("{->" + getDocumentNo() + "}");
		reversal.sethrm_total(gethrm_total().negate());

		Mhrmcheckoffline[] iLines = reversal.getLinesCheckoff();
		for (int i = 0; i < iLines.length; i++)
		{
			Mhrmcheckoffline iLine = iLines[i];
			iLine.sethrm_amount(iLine.gethrm_amount().negate());
			iLine.sethrm_total(iLine.gethrm_total().negate());
			iLine.saveEx(get_TrxName());
        }
		setProcessed(true);
		
		reversal.setReversal_ID(gethrm_checkoff_ID()); // TODO
		reversal.saveEx(get_TrxName());
		if (!reversal.processIt(DocAction.ACTION_Complete))	{
			m_processMsg = "Reversal ERROR: " + reversal.getProcessMsg();
			return false;
		}
		reversal.closeIt();
		reversal.setProcessing (false);
		reversal.setDocStatus(DOCSTATUS_Drafted);
		reversal.setDocAction(DOCACTION_Complete);
		reversal.saveEx(get_TrxName());
		m_processMsg = reversal.getDocumentNo();
		setReversal_ID(reversal.gethrm_checkoff_ID());
		addDescription("{" + reversal.getDocumentNo() + "<-}");
		return true;
	}
	
	public static Mhrmcheckoff copyFrom (Mhrmcheckoff from, 
										Timestamp startDt, 
										Timestamp endDt, 
										Timestamp dateAcct, 
										String trxName) {
		Mhrmcheckoff to = new Mhrmcheckoff(from.getCtx(), 0, trxName);
		copyValues(from, to);
		
		to.set_ValueNoCheck (X_hrm_checkoff.COLUMNNAME_hrm_checkoff_ID, I_ZERO);
		//
		to.setDocStatus (DOCSTATUS_Drafted);		//	Draft
		to.setDocAction(DOCACTION_Complete);
		//
		to.setStartDate(startDt);
		to.setEndDate(endDt);
		to.setDateAcct (dateAcct);
		//
		to.setIsApproved (false);
		//
		to.setIsTransferred (false);
		to.setPosted (false);
		to.setProcessed (false);
		//[ 1633721 ] Reverse Documents- Processing=Y
		to.setProcessing(false);
		//	delete references
		to.saveEx(trxName);

		//	Lines
		// Check lines exist before copy
		if ( from.getLinesCheckoff().length > 0 )
		{
			if (to.copyListLinesFrom(from) == 0)
				throw new IllegalStateException("Could not create List");
		}
		
		return to;
	}
	
	public int copyListLinesFrom (Mhrmcheckoff other) {
		if (isProcessed() || isPosted() || other == null)
			return 0;
		Mhrmcheckoffline[] fromLines = other.getLinesCheckoff();
		int count = 0;
		for (int i = 0; i < fromLines.length; i++)
		{
			Mhrmcheckoffline line = new Mhrmcheckoffline (getCtx(), 0, get_TrxName());
			Mhrmcheckoffline fromLine = fromLines[i];
			PO.copyValues (fromLine, line, fromLine.getAD_Client_ID(), fromLine.getAD_Org_ID());
			line.sethrm_checkoff_ID(gethrm_checkoff_ID());
			line.set_ValueNoCheck (X_hrm_checkoff_line.COLUMNNAME_hrm_checkoff_line_ID, I_ZERO);	// new
			if (line.save(get_TrxName()))
				count++;
		}
		if (fromLines.length != count)
			log.log(Level.SEVERE, "Line difference - From=" + fromLines.length + " <> Saved=" + count);
		return count;
	}
	
	public void addDescription (String description)
	{
		String desc = getDescription();
		if (desc == null)
			setDescription(description);
		else
			setDescription(desc + " | " + description); 
	}	//	addDescription 
	
	/** Reversal Flag		*/
	private boolean m_reversal = false;

	/**
	 * 	Is Reversal
	 *	@return reversal
	 */
	public boolean isReversal()
	{
		return m_reversal;
	}	//	isReversal

	/**
	 * 	Set Reversal
	 *	@param reversal reversal
	 */
	private void setReversal(boolean reversal)
	{
		m_reversal = reversal;
	}	//	setReversal

	public boolean reverseAccrualIt() {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean reActivateIt() {
		setDocStatus(STATUS_Drafted);
		setDocAction(DOCACTION_Complete);
		setProcessed(false);
		setPosted(false);
		return true;
	}

	public String getSummary() {
		// TODO Auto-generated method stub
		return null;
	}

	public String getDocumentInfo() {
		// TODO Auto-generated method stub
		return null;
	}

	public File createPDF() {
		// TODO Auto-generated method stub
		return null;
	}

	public String getProcessMsg() {
		// TODO Auto-generated method stub
		return null;
	}

	public int getDoc_User_ID() {
		// TODO Auto-generated method stub
		return 0;
	}
	
	public BigDecimal getApprovalAmt() {
		// TODO Auto-generated method stub
		return null;
	}
	
	public static Mhrmcheckoff get (Properties ctx, int hrm_checkoff_ID)
	{
		Integer key = new Integer (hrm_checkoff_ID);
		Mhrmcheckoff retValue = (Mhrmcheckoff) s_cache.get (key);
		if (retValue != null)
			return retValue;
		retValue = new Mhrmcheckoff (ctx, hrm_checkoff_ID, null);
		if (retValue.get_ID () != 0)
			s_cache.put (key, retValue);
		return retValue;
	} //	get

	/**	Cache						*/
	private static CCache<Integer,Mhrmcheckoff>	s_cache	= new CCache<Integer,Mhrmcheckoff>("hrm_checkoff", 20, 2);	//	2 minutes
	
}
